<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="bar">
    <div class="left-button-group">
      <div class="bar-item icon-list">
        <template v-if="has_permission() && !viewVersion">
          <el-tooltip v-if="!instanceRunning && !instancePaused" class="item" effect="dark" content="运行 (Ctrl + R)"
            placement="bottom">
            <el-button name="runModule" size="small" @click="handleClick">
              <div class="svgIconBox">
                <svg-icon-file icon-class="yunhang4" />
              </div>
            </el-button>
          </el-tooltip>
          <el-tooltip v-if="instanceRunning" class="item" effect="dark" content="暂停" placement="bottom">
            <el-button name="workflowPaused" size="small" @click="handleClick">
              <div class="svgIconBox">
                <svg-icon-file icon-class="zanting1" />
              </div>
            </el-button>
          </el-tooltip>
          <el-tooltip v-if="instancePaused" class="item" effect="dark" content="继续运行" placement="bottom">
            <el-button name="workflowResume" size="small" @click="handleClick">
              <div class="svgIconBox">
                <svg-icon-file icon-class="yunhang3" />
              </div>
            </el-button>
          </el-tooltip>
          <el-tooltip v-if="!instanceRunning && store.instanceId" class="item" effect="dark" content="重新运行"
            placement="bottom">
            <el-button name="workflowScheduled" size="small" @click="handleClick">
              <div class="svgIconBox">
                <svg-icon-file icon-class="yunhangjiankong" />
              </div>
            </el-button>
          </el-tooltip>
          <el-tooltip v-if="instanceRunning || instancePaused" class="item" effect="dark" content="取消运行"
            placement="bottom">
            <el-button name="workflowCancelled" size="small" @click="handleClick">
              <div class="svgIconBox">
                <svg-icon-file icon-class="yunhangshibai" />
              </div>
            </el-button>
          </el-tooltip>
          <el-divider direction="vertical" />
        </template>
        <template v-if="viewVersion">
          <el-tooltip v-if="has_permission()" class="item narrow" effect="dark" content="编辑" placement="bottom">
            <el-button name="updateVersion" size="small" @click="historicalVersionHandle">
              <svg-icon icon-class="xiugai-copy" />
            </el-button>
          </el-tooltip>
          <el-tooltip class="item narrow" effect="dark" content="查看关联实验" placement="bottom">
            <el-button name="correlation" size="small" @click="historicalVersionHandle">
              <svg-icon icon-class="guanliansousuo" />
            </el-button>
          </el-tooltip>
          <el-tooltip v-if="has_permission()" class="item" effect="dark" content="还原至此版本" placement="bottom">
            <el-button name="reduction" size="small" @click="historicalVersionHandle">
              <svg-icon icon-class="shanchuhuanyuan" />
            </el-button>
          </el-tooltip>
          <el-tooltip v-if="has_permission()" class="item" effect="dark" content="删除此版本" placement="bottom">
            <el-button name="delete" size="small" @click="historicalVersionHandle">
              <svg-icon icon-class="icon" />
            </el-button>
          </el-tooltip>
        </template>
        <template v-else>
          <el-tooltip class="item" effect="dark" content="清空画布" placement="bottom">
            <el-button name="init" size="small" @click="handleClick">
              <div class="svgIconBox">
                <svg-icon-file icon-class="qingkong" />
              </div>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="复制 (Ctrl + C)" placement="bottom">
            <el-button :disabled="!store.copy" name="copy" size="small" @click="handleClick">
              <div class="svgIconBox">
                <svg-icon-file icon-class="fuzhi1" />
              </div>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="粘贴 (Ctrl + V)" placement="bottom">
            <el-button :disabled="!store.paste" name="paste" size="small" @click="handleClick">
              <div class="svgIconBox">
                <svg-icon-file icon-class="niantie1" />
              </div>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="保存 (Ctrl + S)" placement="bottom">
            <el-button name="print" size="small" @click="handleSave">
              <div class="svgIconBox">
                <svg-icon-file icon-class="baocun1" />
              </div>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="保存为新版本" placement="bottom">
            <el-button name="print" size="small" @click="handleSaveVersion">
              <div class="svgIconBox">
                <svg-icon-file icon-class="baocunbanben" />
              </div>
            </el-button>
          </el-tooltip>
        </template>
      </div>
      <div v-if="store.workflowSaveState" class="auto-save">
        <span v-if="store.workflowSaveState === workflowSaveStateCode.loading">
          <el-icon style="vertical-align: middle;margin-top: -1px;">
            <RefreshRight />
          </el-icon>
          <span>数据正在保存中...</span>
        </span>
        <span v-if="store.workflowSaveState === workflowSaveStateCode.success">
          <el-icon style="vertical-align: middle;margin-top: -1px; color:rgb(63, 189, 0)">
            <CircleCheck />
          </el-icon>
          <span>{{ store.workflowSaveTime }} 保存成功</span>
        </span>
        <span v-if="store.workflowSaveState === workflowSaveStateCode.error">
          <el-icon style="vertical-align: middle;margin-top: -1px; color:rgb(227, 19, 19)">
            <CircleClose />
          </el-icon>
          <span>{{ store.workflowSaveTime }} 保存失败</span>
        </span>
      </div>
    </div>
    <div class="right-button-group">
      <el-button v-if="has_permission()" size="mini" type="primary" @click="addExperimentDialogFun()">创建实验</el-button>
    </div>
    <save-version-dialog v-if="saveVersionDialogVisible" ref="saveVersionDialogRef" />
    <add-experiment-dialog v-if="addExperimentDialogVisible" ref="addExperimentDialogRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from "vue"
import { designerStore } from 'src/stores/designerTool/designerTool'
import { instancesState, instancesStateText, workflowSaveStateCode } from 'src/utils/designerTool/constants'
import { formatDate } from 'src/utils/designerTool/toole';
import Mousetrap from 'mousetrap'
import SaveVersionDialog from 'src/pages/designerTool/canvas/RightProperty/saveVersionDialog.vue'
import AddExperimentDialog from 'src/pages/designerTool/canvas/FlowChartRight/addExperimentDialog.vue'
import dagGraph from 'src/pages/designerTool/canvas/DagEdit/graph/index.js'
import { ElMessage, ElMessageBox } from 'element-plus';
import SvgIconFile from './svgIcon.vue'
const saveVersionDialogVisible = ref(false)
const addExperimentDialogVisible = ref(false)
const store = designerStore()
const saveVersionDialogRef = ref(null)
const addExperimentDialogRef = ref(null)
const has_permission = () => {
  return true
}
const instanceRunning = computed(() => {
  return store.instanceState === instancesState.Running
})
const instancePaused = computed(() => {
  return store.instanceState === instancesState.Paused
})
const saveTime = computed(() => {
  return store.workflowSaveTime ? formatDate(store.workflowSaveTime) : ''
})
const viewVersion = computed(() => {
  return !!store.versionId
})
const viewExperiment = computed(() => {
  return !!store.experimentId || !!store.flowReadonlyId
})
const readonly = computed(() => {
  return viewVersion.value || viewExperiment.value
})
watch(() => store.selectedId, (newData, oldData) => {
  const bol = !!newData
  store.SET_COPY(bol)
  store.SET_CUT(bol)
  if (!bol) {
    store.SET_PASTE(bol)
  }
})
watch(() => store.events.initEvent.index, (newData, oldData) => {

  initEvent()
})
watch(() => store.events.workflowSave.index, (newData, oldData) => {
  handleSave()
})
function initEvent() {
  if (!readonly.value) {
    const { history } = dagGraph.graph
    history.on('change', () => {
      // 是否可以撤销。
      store.SET_UNDO(history.canUndo())
      // 是否可以重做。
      store.SET_REDO(history.canRedo())
    })
    // 复制
    dagGraph.graph?.bindKey('ctrl+c', () => {
      dagGraph.copyNode()
      return false
    })
    // 粘贴
    dagGraph.graph?.bindKey('ctrl+v', () => {
      dagGraph.pasteNode()
      return false
    })
    // 上一步
    Mousetrap.bind('ctrl+z', () => {
      if (history.canUndo()) {
        history.undo()
      }
      return false
    })
    // 下一步
    Mousetrap.bind('ctrl+shift+z', () => {
      if (history.canRedo()) {
        history.redo()
      }
      return false
    })
    // 清空画布。
    // Mousetrap.bind('ctrl+d', () => {
    //   dagGraph.graph.clearCells()
    //   return false
    // })
    // 保存
    Mousetrap.bind('ctrl+s', () => {
      handleSave()
      return false
    })
    // 保存图片
    // Mousetrap.bind('ctrl+p', () => {
    //   dagGraph.graph.printPreview()
    //   return false
    // })
  }
  if (!viewExperiment.value) {
    // 运行
    Mousetrap.bind('ctrl+r', () => {
      if (!instanceRunning.value) {
        handleClick({
          currentTarget: {
            name: 'runModule'
          }
        })
      }
      return false
    })
  }
}
function cutHandle() {
  // 剪切
  const cells: any = dagGraph.graph?.getSelectedCells()
  if (cells.length) {
    dagGraph.graph?.cut(cells)
    store.SET_PASTE(true)
  }
  return false
}
function handleClick(event: any) {
  const name = event.currentTarget.name
  switch (name) {
    case 'init': {
      ElMessageBox.confirm('确定要清空画布,所有数据节点将被清空,是否清空?', '清空画布', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        initGraph()
        store.SET_INSTANCE_STATE('')
      }).catch(() => {
        console.log()
      })
      break
    }
    case 'undo':
      dagGraph.graph?.history.undo()
      break
    case 'redo':
      dagGraph.graph?.history.redo()
      break
    case 'print':
      dagGraph.graph?.printPreview()
      break
    case 'copy':
      dagGraph.copyNode()
      break
    case 'cut':
      cutHandle()
      break
    case 'paste':
      dagGraph.pasteNode()
      break
    case 'runModule':
    case 'workflowScheduled':
    case 'workflowPaused':
    case 'workflowResume':
    case 'workflowCancelled':

      store.SET_PUBLISH_EVENT({
        key: 'updateRunState',
        data: {
          key: name,
          disabled: false
        }
      })
      break
    default:
      break
  }
}
function initGraph() {
  dagGraph.graph?.clearCells()
  dagGraph.graph?.center() // 内容居中
  dagGraph.graph?.zoomTo(1) // 缩放比例
}
function handleSave() {
  if (store.workflowSaveState === workflowSaveStateCode.loading) {
    return
  }
  dagGraph.saveOrUpdateWorkflowData().then(res => {
    console.log()
  }, res => {
    ElMessage(res.result)
  }).finally(() => {
    console.log()
  })
}
function handleSaveVersion() {
  saveVersionDialogVisible.value = true
  nextTick(() => {
    (saveVersionDialogRef.value as any).init()
  })
}
function addExperimentDialogFun() {
  addExperimentDialogVisible.value = true
  nextTick(() => {
    (addExperimentDialogRef.value as any).init()
  })
}
function historicalVersionHandle(event: any) {
  let randomNum=Math.random()
  store.SET_PUBLISH_EVENT({
    key: 'historicalVersionHandle',
    data: event.currentTarget.name,
    versionOperate:randomNum
  })
}


</script>

<style lang="scss" scoped>
@import "src/css/designerStyles/index.scss";
@import "./index.scss";

.svgIconBox {
  transform: scale(0.85);
}
</style>
